// eslint-disable-next-line strict
const fs = require('fs');
exports.buildValidateOfModel = Model => {
  const { paths } = Model.schema;

  buildFrontEndValidate(Model);

  const rules = {
    create: {},
    update: {},
  };
  const whiteList = [ 'createdAt', 'updatedAt' ];
  Object.keys(paths)
    .forEach(field => {
      if (!field.startsWith('_') && !whiteList.includes(field)) {
        const type = toValidateType(paths[field].instance);
        if (type) {
          rules.create[field] = {
            type,
            required: !!paths[field].originalRequiredValue,
            validators: paths[field].validators,
          };
          rules.update[field] = {
            type,
            required: false,
            validators: paths[field].validators,
          };
        }
      }
    });

  Model.rules = rules;

  return Model;
};

function toValidateType(type) {
  switch (type) {
    case 'Boolean': {
      return 'boolean';
    }
    case 'ObjectID':
    case 'String': {
      return 'string';
    }
    case 'Number': {
      return 'number';
    }
    case 'Date': {
      return 'string';
    }
    default:
      return null;
  }
}

function buildFrontEndValidate(Model) {
  const { paths } = Model.schema;
  const validate = {
    toString() {
      const results = {};
      Object.keys(this)
        .forEach(field => {
          if (field === 'toString') return false;
          results[field] = [];
          this[field].forEach(item => {
            results[field].push(item.validator.toString() + ' || `' + item.message + '`');
          });
          if (paths[field].originalRequiredValue) {
            results[field][0] = (v => !!v || '必填项').toString();
          }
        });
      let str = 'export default {\n';
      for (const key of Object.keys(results)) {
        str += `  "${key}": [\n`;
        for (const item of results[key]) {
          str += `    ${item},\n`;
        }
        str += '  ],\n';
      }
      str = str.replace(/"(function.+)"|"(.+=>.+)"/g, '$1$2');
      str = str.replace(/\{VALUE\}/g, '${v}');
      str += '}';
      return str;
    },
  };
  const whiteList = [ 'createdAt', 'updatedAt', 'status' ];
  Object.keys(paths)
    .forEach(field => {
      if (!field.startsWith('_') && !whiteList.includes(field)) {
        validate[field] = paths[field].validators;
      }
    });
  const path = `${process.cwd()}/validate`;
  if (!fs.existsSync(path)) {
    fs.mkdirSync(path);
  }
  // fs.writeFileSync(`${path}/${Model.modelName.toLowerCase()}.js`, validate.toString());
  return validate;
}
